package com.server.core.handler;

import com.alibaba.fastjson.JSON;
import com.common.GZipUtils;
import com.common.Msg;
import com.common.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ActionHandler extends SimpleChannelInboundHandler<Msg> {

    public final static Map<String, ChannelHandlerContext> Users = new HashMap<>();

    /**
     * 文件交换业务
     *
     * @param channelHandlerContext
     * @param res
     * @throws Exception a-O-b
     */
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Msg res) throws Exception {

        switch (res.getType()) {
            case CONNECT:
                System.out.println("服务器已经添加了一个人");
                String me = res.getMe();
                Users.put(me, channelHandlerContext);
                break;
            case SEND_MSG:
                String he = res.getHe();
                String me1 = res.getMe();
                Users.get(he).writeAndFlush(MsgUtil.REC_MSG(he, me1, res.getBytes()));
                break;
            case GET_GROUP:
                String me2 = res.getMe();
                Set<String> strings = Users.keySet();
                Users.get(me2).writeAndFlush(MsgUtil.REC_GROUP(me2, JSON.toJSONString(strings)));
                break;
            case START_FILE:
                String he1 = res.getHe();
                Users.get(he1).writeAndFlush(MsgUtil.START_FILE(he1, res.getMe(), GZipUtils.ungzip(res.getBytes())));
                break;
            case SEND_FILE:
                //终于写到文件了
                Users.get(res.getHe()).writeAndFlush(MsgUtil.REC_FILE(res.getHe(), res.getMe(), GZipUtils.ungzip(res.getBytes()), GZipUtils.ungzip(res.getFile())));
                break;
            case OK_FILE:
                Users.get(res.getHe()).writeAndFlush(MsgUtil.OK_FILE(res.getHe(), res.getMe(), new String(GZipUtils.ungzip(res.getBytes()))));
                break;
            case REQ_FILE:
                //告诉发送方，需求文件，然后读取文件
                String he2 = res.getHe();
                String me3 = res.getMe();
                Users.get(he2).writeAndFlush(MsgUtil.REQ_FILE(he2, me3, GZipUtils.ungzip(res.getBytes())));
                break;
        }
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
